package com.xiaobaibai.units;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiaobaibai.bo.BargainDelayItem;
import com.xiaobaibai.bo.OrderDelayItem;
import com.xiaobaibai.common.WeixinCommon;
import com.xiaobaibai.entity.BargainUser;
import com.xiaobaibai.service.IBargainUserService;
import com.xiaobaibai.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.DelayQueue;

/**
 * 对待支付订单的延时队列
 */
@Component
@Slf4j
@Order(999)
public class OrderNoPayDelayQueueUnit implements ApplicationRunner, DisposableBean {

    @Autowired
    private IOrderService orderService;

    private DelayQueue<OrderDelayItem> delayQueue=new DelayQueue<>();

    private List<String> list=new ArrayList<>();//及时保存

    /**
     * 存入延时队列,用redis做半持久化
     */
    public void saveOrderDelayItem(OrderDelayItem orderDelayItem){
        delayQueue.add(orderDelayItem);
        list.add(orderDelayItem.getOrderId());
    }

    private void consumerOrderItem(){
        while (true){
            try {
                OrderDelayItem orderDelayItem = delayQueue.take();
                //取消订单延时队列专用方法,内部已经顾虑了订单状态
                orderService.cancelOrder(orderDelayItem.getOrderId());
                list.remove(orderDelayItem.getOrderId());
            } catch (Exception e) {
                e.printStackTrace();
                log.error("订单取消队列异常");
            }
        }
    }

    @Override
    public void run(ApplicationArguments args) {
        //开始循环
        Thread thread=new Thread(this::consumerOrderItem);
        thread.start();
    }

    @Override
    public void destroy() {
        log.info("容器销毁中,现取消所有未支付的订单");
        for(int i=0;i<list.size();i++){
            String orderId = list.get(i);
            orderService.cancelOrder(orderId);//取消并且返还优惠券+砍价商品
            log.info("取消订单:"+orderId);
        }
        log.info("取消所有订单完毕");
    }

}
